<template>
  <div>
    <page-view>
      <template #option>
        <div class="btn-box">
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="primary" @click="handSetting" :disabled="selectList.length==0">权限设置</el-button>
        </div>
      </template>

      <template #form>

        <search-form :data-form="searchData" @on-search="handleSearch" @on-reset="handleReset">
          <el-form-item prop="bizTypeName">
            <el-select v-model="searchData.bizTypeName" placeholder="请选择业务类型" clearable @change="bizTypeChange">
              <el-option v-for="item in bizTypeList" :key="item.typeName" :value="item.typeName"
                :label="item.typeName" />
            </el-select>
          </el-form-item>
          <el-form-item prop="subBizCodes">
            <subBizSelect v-model:value="searchData.subBizCodes" :bizTypeName="searchData.bizTypeName" emit-path/>
          </el-form-item>
          <el-form-item prop="writeFormName">
            <el-input v-model="searchData.writeFormName" clearable placeholder="请输入表单名称" />
          </el-form-item>
          <el-form-item prop="writeFormCode">
            <el-input v-model="searchData.writeFormCode" clearable placeholder="请输入表单编号" />
          </el-form-item>
        </search-form>
      </template>
      <template #table="tableScope">
        <pubilc-table :table-data="tableData" :isSlot="false" :tableHeight="tableScope.tableHeight"
          :list-config="columns" :page-data="pageData" :showSelect="true" :action-limit="actionLimit"
          :linkLoading="linkLoading"
          @on-action="handleAction" @on-selectChange="onSelectChange" @on-linkClick="onLinkClick" />
      </template>
    </page-view>
    <add-dialog v-if="addVisible" :biz-type-list="bizTypeList" @close="handleClose('addVisible')"
      @refresh="handleRefresh" :pageType="pageType" ref="addRef" />
    <relate-dialog v-if="relateVisible" :relate-form="actionForm" @close="handleClose('relateVisible')"
      @refresh="handleRefresh" />
    <WriteFormPermissionVue v-if="setVisible" @close="handleClose('setVisible')" :selectList="selectList"
      @on-update="handleSearch">
    </WriteFormPermissionVue>
    <SiglePermiseeionSettingVue :dialogVisible="dialogVisibleScope" v-if="dialogVisibleScope" :scopeInfo="scopeInfo"
      @handleClose="handleClose('dialogVisibleScope')" @on-update="handleSearch" :selectList="rowList">
    </SiglePermiseeionSettingVue>
  </div>
</template>
<script>
/*
* File Created: 2022-02-14 09:35:48
* Author: yubaolin (yubaolin6@outlook.com)
* Desc: 填报类表单配置
* Last Modified: 2022-02-14 09:57:08
* Modified By: yubaolin (yubaolin6@outlook.com>)
*/
import {
  reactive,
  onMounted,
  toRefs,
  ref,
  nextTick
} from "vue";
import { useRouter, useRoute } from 'vue-router'
import AddDialog from './components/AddDialog.vue'
import RelateDialog from './components/RelateDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatListToTree } from "@/util/index";
import WriteFormPermissionVue from "./components/writeFormPermission.vue";
import SiglePermiseeionSettingVue from "./components/siglePermiseeionSetting.vue";
import api from '@/api/index'
import { useUserStore } from '@/store/modules/user'

export default {
  // name: "WriteFormConfig",
  components: {
    AddDialog,
    RelateDialog,
    WriteFormPermissionVue,
    SiglePermiseeionSettingVue
  },
  setup() {
    const subBizTypeRef = ref(null)
    const $router = useRouter()
    const userStore = useUserStore()

    // 操作
    const opertate = [
      { alias: "copy", label: "复制" },
      { alias: "edit", label: "编辑" },
      { alias: "editForm", label: "编辑表单" },
      { alias: "del", label: "删除" },
      { alias: "setting", label: "权限设置" },
      // 取消了移动端的设计器
      // { alias: "relate", label: "关联表单" },
    ];

    const state = reactive({
      linkLoading: false,
      searchData: {
        formCode: "",
        formName: "",
        bizTypeName: "",
        subBizCodes: []
      },
      pageData: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableData: [],
      // 业务类型
      bizTypeList: [],
      // 业务子类
      subBizTypeList: [],
      subBizTypeProps: {
        emitPath: false,
        value: 'id',
        label: 'subBizName',
      },
      // 列配置
      columns: [
        { alias: 'formName', label: '表单名称', minWidth: '200' },
        { alias: 'formCode', label: '表单编号', minWidth: '220' },
        { alias: 'bizTypeName', label: '业务类型', minWidth: '180' },
        { alias: 'subBizTypeName', label: '业务子类', minWidth: '180', type: 'link', },
        { alias: 'createTime', label: '创建日期', minWidth: '180' },
        { label: '操作', listArr: opertate, width: '320px', type: 'action' }
      ],
      addVisible: false,
      relateVisible: false,
      // 当前操作表单row数据
      actionForm: null,
      pageType: 'add',
      addRef: null,
      setVisible: false,
      selectList: [],
      dialogVisibleScope: false,
      scopeInfo: '',
      rowList:[]

    });

    const methods = {
      // 请求业务类型列表
      requestBusinessTypeList() {
        api.reimbursement.getBizTypeList({ pageNum: 1, pageSize: 5000 }).then(({ list }) => {
          state.bizTypeList = list
        })
      },
      // 请求业务子类列表
      requestSubBusinessTypeList(bizTypeName) {
        state.subBizTypeList = []
        if (!bizTypeName) {
          return
        }
        api.reimbursement.getSubTypeListByBizName(bizTypeName).then(data => {
          state.subBizTypeList = formatListToTree(data)
        })
      },
      // 请求表单列表
      requestList() {
        api.writeForm.writeFormPageList({
          ...state.searchData,
          subBizCodes: state.searchData.subBizCodes.flat(),
          ...state.pageData,
        }).then(data => {
          state.tableData = data.list || []
          state.pageData.total = data.total || 0
        })
      },
      // 表格操作去表单页
      editForm: (row) => {
        // todo 表单编辑
        $router.push({ path: '/design/composite-designer', query: { formCode: row.formCode } })
      },
      // 表格操作复制
      copy: (row) => {
        state.pageType = 'copy'
        state.addVisible = true
        nextTick(() => {
          let curRow = { ...row }
          curRow.formName = ''
          state.addRef.formData = curRow
        })

      },
      // 表格操作编辑
      edit: (row) => {
        state.pageType = 'edit'
        state.addVisible = true
        nextTick(() => {
          console.log(state.addRef, row)
          let curRow = { ...row }
          state.addRef.formData = curRow

        })

      },
      // 表格操作删除
      del: (row) => {
        ElMessageBox.confirm(
          '您确定要进行删除操作吗?',
          '温馨提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          api.writeForm.delWriteForm(row.id).then(() => {
            methods.requestList()
            ElMessage.success('操作成功')
          })
        })
      },
      setting(row) {
        console.log(row)
        state.rowList = [row]
        state.dialogVisibleScope = true

      },
      // 表格操作关联表单
      relate: (row) => {
        state.relateVisible = true
        state.actionForm = row
      },
      pageNum: (page) => {
        state.pageData.pageNum = page;
        methods.requestList()
      },
      pageSize: (size) => {
        state.pageData.pageNum = 1;
        state.pageData.pageSize = size;
        methods.requestList()
      },

    };

    const handles = {
      onLinkClick([name, row]) {
        if (name === 'subBizTypeName') {
          state.linkLoading = true
          api.reimbursement.getSubBizTypePath(row.subBizTypeCode).then((res) => {
            ElMessageBox.alert(res, '业务子类完整路径', {
              closeOnClickModal: true
            })
            state.linkLoading = false
          }).catch(() => {
            state.linkLoading = false
          })
        }
      },
      onSelectChange(list) {
        console.log(list)
       state.selectList = list
      },
      // 权限调协
      handSetting() {
        state.setVisible = true
      },
      // 搜索
      handleSearch() {
        state.pageData.pageNum = 1
        methods.requestList()
      },
      // 重置
      handleReset() {
        state.searchData.subBizTypeName = '';
        state.searchData.bizTypeCode = ''
        state.searchData.bizTypeName = ''
        methods.pageNum(1);
      },
      // 新增按钮
      handleAdd() {
        state.pageType = 'add'
        state.addVisible = true
      },
      // 表格操作
      handleAction([item, params]) {
        console.log(item, 'item', params)
        const handleName = typeof item === 'string' ? item : item.alias;
        const handle = methods[handleName]
        handle && handle(params);
      },
      // 业务类型改变
      bizTypeChange(bizTypeName) {
        state.searchData.bizTypeCode = ''
        state.searchData.subBizTypeId = ''
        state.searchData.subBizTypeName = ''
        state.bizTypeList.forEach(item => {
          if (item.typeName === bizTypeName) {
            state.searchData.bizTypeCode = item.typeCode
          }
        })
        // methods.requestSubBusinessTypeList(bizTypeName)
      },
      subTypeChange(subTypeId) {
        let checkItem = subBizTypeRef.value.getCheckedNodes(true)
        if (checkItem && checkItem.length > 0) {
          state.searchData.subBizTypeName = checkItem[0].data.subBizName
        }
      },
      handleClose(visibleField) {
        state[visibleField] = false
      },
      handleRefresh() {
        methods.requestList()
      },
      actionLimit([row, action]) {
        if (action.alias == 'del') {
          return row.bizTypeCode == 'BUDGET'
        }
        // if(action.alias == 'relate') {
        //     return row.relatedFormId
        // }
        return false
      }
    }


    onMounted(() => {
      methods.requestBusinessTypeList()
      methods.requestList()
      userStore.getWorkePosition // 获取岗位
    })

    return {
      subBizTypeRef,
      ...toRefs(state),
      ...handles,
    };
  },
};

</script>
<style lang="scss" scoped>
</style>
